package kit.docker.log;

import com.jfinal.kit.StrKit;
import org.apache.log4j.*;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;

public class LoggerKit {

    private static LoggerKit log = new LoggerKit();

    private LoggerKit() {
    }

    public static LoggerKit getInstance() {
        return log;
    }

    public Logger create(String filePath, String fileName) {
        return create(filePath, fileName, "", true);
    }

    public Logger create(String filePath, String fileName, String conversionPattern) {
        return create(filePath, fileName, conversionPattern, true);
    }

    /**
     * 生成日志对象
     *
     * @param filePath          日志输出路径
     * @param fileName          日志文件名
     * @param conversionPattern Log输出形式
     * @param flag              true:在已存在的Log文件后面追加，false:新Log覆盖之前的Log
     * @return
     */
    public Logger create(String filePath, String fileName, String conversionPattern, boolean flag) {
        // 生成新的Logger 如果已经有了一个Logger实例则返回
        Logger logger = Logger.getLogger(fileName);
        // 清空Appender。特别是不想使用现存实例时一定要初始化。
        logger.removeAllAppenders();
        ;
        // 设定Logger级别
        logger.setLevel(Level.DEBUG);
        // 设定是否继承父Logger,默认为true,继承root输出，设定false后将不输出root
        logger.setAdditivity(false);
        // 生成新的Appender
        FileAppender appender = new RollingFileAppender();
        // Log的输出形式
        PatternLayout layout = new PatternLayout();
        if (StrKit.isBlank(conversionPattern)) {
            // [%d] %p %t %c - %m%n
            layout.setConversionPattern("[%d] %p %t - %m%n");
        } else {
            layout.setConversionPattern(conversionPattern);
        }
        appender.setLayout(layout);

        //Log输出路径
        appender.setFile(filePath + fileName + ".log");
        // Log文字编码格式
        appender.setEncoding("UTF-8");
        // Log写入模式
        appender.setAppend(flag);
        // 适用当前配置
        appender.activateOptions();
        // 将新的Appender加入到Logger中
        logger.addAppender(appender);
        return logger;

    }

    public void close(Logger logger) {
        for (Enumeration<Appender> appenders = logger.getAllAppenders(); appenders.hasMoreElements(); ) {
            Appender appender = appenders.nextElement();
            appender.close();
        }
    }

    public static String getExceptionTrace(Throwable e) {
        if (e != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return sw.toString();
        }
        return "No Exception";
    }

}
